package com.example.lenovo.test1;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import java.lang.reflect.Method;
import java.util.ArrayList;

public class Main3Activity extends AppCompatActivity {
    private TextView mtvTitle;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);
        bindWidget();
    }
    protected void bindWidget() {
        mtvTitle = findViewById(R.id.mtvTitle);



    }
    private void setIconsVisible(Menu menu, boolean flag) {

        if (menu != null) {//判断menu是否为空
            try {
                Method method = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);//如果不为空,就反射拿到menu的setOptionalIconsVisible方法
                method.setAccessible(true); //暴力访问该方法
                method.invoke(menu, flag);//调用该方法显示icon
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        setIconsVisible(menu,true);
        MenuInflater menuInflater =  getMenuInflater();
        menuInflater.inflate(R.menu.context_menu,menu);
//        MenuItem menuItem =  menu.add(Menu.NONE, Menu.FIRST + 1, 1, "菜单一");
//        menuItem.setIcon(R.drawable.update);
//        menuItem = menu.add(Menu.NONE, Menu.FIRST + 2, 2, "菜单二");
//        menuItem.setIcon(R.drawable.about);
//
//
//        SubMenu subMenu = menu.addSubMenu(Menu.NONE, Menu.FIRST + 3, 3, "菜单三");
//        subMenu.setIcon(R.drawable.exit);
//        subMenu.add(Menu.NONE, Menu.FIRST + 4, 1, "二级菜单1").setIcon(R.drawable.update);
//        subMenu.add(Menu.NONE, Menu.FIRST + 5, 2, "二级菜单2").setIcon(R.drawable.about);

        return super.onCreateOptionsMenu(menu);
    }
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case Menu.FIRST + 1:
                mtvTitle.setText("菜单一");
                break;
            case Menu.FIRST + 2:
                mtvTitle.setText("菜单二");
                break;
            case Menu.FIRST + 3:
                mtvTitle.setText("菜单三");
                break;
            case Menu.FIRST + 4:
                mtvTitle.setText("二级菜单1");
                break;
            case Menu.FIRST + 5:
                mtvTitle.setText("二级菜单2");
                break;
            default:
                return super.onOptionsItemSelected(item);
        }
        return super.onOptionsItemSelected(item);
    }

}